package utility;

import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ResizeImage {
	/**
	 * Funkcija za promenu velicine slike
	 * @param image Slika u kompatibilan (BufferedImage) formatu
	 * @param width Zeljena sirina slike
	 * @param height Zeljena visina slike
	 * @return Novi BufferedImage 
	 */
	public static BufferedImage createResizedCopy(BufferedImage image, int width, int height) { 
		int type = image.getType() == 0? BufferedImage.TYPE_INT_ARGB : image.getType();
		BufferedImage resizedImage = new BufferedImage(width, height, type);
		Graphics2D g = resizedImage.createGraphics();
		g.setComposite(AlphaComposite.Src);

		g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, 
		RenderingHints.VALUE_INTERPOLATION_BILINEAR);

		g.setRenderingHint(RenderingHints.KEY_RENDERING, 
		RenderingHints.VALUE_RENDER_QUALITY);

		g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
		RenderingHints.VALUE_ANTIALIAS_ON);

		g.drawImage(image, 0, 0, width, height, null);
		g.dispose();
		return resizedImage;
	}
	
	public static boolean Resize(File f, int width, int height) { 
		BufferedImage bufferedImage = null;
		try {
			bufferedImage = ImageIO.read(f);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		int lastIdx = f.getAbsolutePath().lastIndexOf('.');
		String ftype = f.getAbsolutePath().substring(lastIdx+1);

		try {
			ImageIO.write(ResizeImage.createResizedCopy(bufferedImage,width, width), ftype,f);
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
}
